import React, { useEffect, useState } from 'react';
import { Button, Typography, Box, Grid, Snackbar, Alert, CircularProgress } from '@mui/material';
import { getCrmRecordById, getCrmRecordFromSql, putdata } from "../../util/util";


//生产发货通知单作废操作
const App = (pagedata) => {
    const [openSnackbar, setOpenSnackbar] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [loading, setLoading] = useState(false); // loading 状态

    useEffect(() => {
        window.ZOHO.CRM.UI.Resize({ height: "300", width: "500" }).then(function (data) {
            console.log(data);
        });
    }, [pagedata]);

    const handleCancel = async () => {
        await window.ZOHO.CRM.UI.Popup.close();
    };

    const handleConfirm = async () => {
        setLoading(true); // 开始loading

        try {
            // 确认操作
            console.log('pagedata', pagedata);
            let entityId = pagedata?.data.EntityId[0];
            let entityName = pagedata?.data.Entity;
            let ressult = await getCrmRecordById(entityName, entityId);
            console.log('ressult', ressult);

            if (ressult) {
                let pscode = ressult?.Name;
                let sqlstr = `select id from LinkingModule9 where PSNoticeNo = '${pscode}' and DataStatus != '作废'`;
                let result_query = await getCrmRecordFromSql(sqlstr);
                // console.log('result_query', result_query);

                if (result_query && result_query.length > 0) {
                    // 显示提醒
                    setSnackbarMessage("此单据已经做了备货通知，无法作废！请先将相关备货通知作废！");
                    setOpenSnackbar(true);
                    setLoading(false); // 停止loading
                    // 延迟一段时间后关闭弹窗
                    setTimeout(async () => {
                        await window.ZOHO.CRM.UI.Popup.close();
                    }, 1500);
                    return;
                } else {
                    let jsondata = { "data": [{ "field7": "待审批", "DataStatus": "作废" }], "trigger": ["workflow"] };
                    let result_up = await putdata(entityName, entityId, jsondata);
                    // console.log('result_up', result_up);
                    console.log('result_up', JSON.stringify(result_up));
                    setSnackbarMessage("成功！");
                    setOpenSnackbar(true);
                    setLoading(false); // 停止loading
                    // 延迟一段时间后关闭弹窗
                    setTimeout(async () => {
                        await window.ZOHO.CRM.UI.closeReload.close();
                    }, 1000);
                    return;
                }
            }
        } catch (error) {

        } finally {
            setLoading(false); // 结束loading
        }
    };

    const handleCloseSnackbar = () => {
        setOpenSnackbar(false);
    };

    return (
        <Box
            display="flex"
            justifyContent="center"
            alignItems="center"
            minHeight="100vh"
            bgcolor="#f5f5f5"
        >
            <Box
                bgcolor="white"
                p={4}
                boxShadow={3}
                borderRadius={2}
                maxWidth="400px"
                textAlign="center"
            >
                <Typography variant="h6" gutterBottom>
                    操作确认
                </Typography>
                <Typography variant="body1" color="textSecondary" gutterBottom>
                    此操作不可恢复，请谨慎操作，是否确认？
                </Typography>
                <Grid container spacing={2} justifyContent="center" mt={2}>
                    <Grid item>
                        <Button variant="outlined" color="primary" onClick={handleCancel}>
                            取消
                        </Button>
                    </Grid>
                    <Grid item>
                        <Button variant="contained" color="error" onClick={handleConfirm}>
                            确定
                        </Button>
                    </Grid>
                </Grid>
                {/* CircularProgress (加载中指示器) */}
                {loading && (
                    <Box
                        position="absolute"
                        top="50%"
                        left="50%"
                        transform="translate(-50%, -50%)"
                    >
                        <CircularProgress />
                    </Box>
                )}
            </Box>

            {/* Snackbar 提示 */}
            <Snackbar
                open={openSnackbar}
                autoHideDuration={4000}
                onClose={handleCloseSnackbar}
            >
                <Alert onClose={handleCloseSnackbar} severity="info">
                    {snackbarMessage}
                </Alert>
            </Snackbar>
        </Box>
    );
};

export default App;
